package buffered_rw;

import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

/*文件复制*/
public class ReaderWriter {
    @Test
    public void test() throws IOException {
        //读写a文件
        BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream("a.txt")));
        // 缓冲自动刷新 只针对  println()   print()则需要手动刷新
        PrintWriter pw = new PrintWriter(
                new OutputStreamWriter(
                        new FileOutputStream("c.txt", true)), true);
        String s = null;
        ArrayList<String> letters = new ArrayList<>();
        while ((s = br.readLine()) != null) {
            String[] words = s.split(" ");
            // 数组转成集合的方法   Arrays.asList(数组)
            // 返回一个集合 要加入另外一个集合，addAll(Collection<T> c);
            letters.addAll(Arrays.asList(words));
            //读取一行就换行

        }

        //读取b文件
        BufferedReader br1 = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream("b.txt")));
        String s1 = null;
        ArrayList<String> letters1 = new ArrayList<>();
        while ((s1 = br1.readLine()) != null) {
            String[] words1 = s1.split(" ");
            // 数组转成集合的方法   Arrays.asList(数组)
            // 返回一个集合 要加入另外一个集合，addAll(Collection<T> c);
            letters1.addAll(Arrays.asList(words1));
            //读取一行就换行


        }

        //写入文件  a b 文件交替
        if (letters.size() >= letters1.size()) {

            for (int i = 0; i < letters.size(); i++) {
                pw.print(letters.get(i) + " ");
                if (i < letters1.size()) {
                    pw.print(letters1.get(i) + " ");
                }
            }
        } else {
            for (int i = 0; i < letters1.size(); i++) {
                if (i < letters.size()) {
                    pw.print(letters.get(i) + " ");
                }
                pw.print(letters1.get(i) + " ");

            }
        }
        //刷新缓冲*/
        pw.flush();
        br.close();
        br1.close();
    }

}
